/// <reference path="../../index.d.ts" />
const Service = require("egg").Service
let helper = require("../extend/helper")
// const hasOwnProperty = Object.prototype.hasOwnProperty;
class AppService extends Service {
	constructor(ctx) {
		super(ctx)
		this.Module = this.app.model.Module
		this.ModuleApplicat = this.app.model.ModuleApplicat
		this.Application = this.app.model.Application
		this.AmoPartci = this.app.model.AmoPartci
		this.UmPartci = this.app.model.UmPartci
		this.ApplicationUser = this.app.model.ApplicationUser
		this.UnionUser = this.app.model.UnionUser
		this.EmpireUserView = this.app.model.EmpireUserView
	}
	/**
   * 开关模块
   * @param {number} aid 
   * @param {number} mid 
   * @param {boolean} stat 
   */
	async changStat(aid, mid, stat) {
		// this.ModuleApplicat.find
		let dat = {stat: 0, msg: "", data: undefined}
		let res = await this.getAppModuleByAidMid(aid, mid)

		if (!res.stat) {
			dat.msg = res.msg + ";不允许操作"
			return dat
		}
		else {
			let updateStat = await this.ModuleApplicat.update({stat: stat}, {where: {aid, mid}})
			if (updateStat.length > 0) {
				dat.stat = true
				dat.msg = "操作成功"
			} else {
				dat.msg = "数据正常,操作失败?"
			}
			return dat
		}
	}

	/**
	 * 获取模块
	 */
	async  getAppModule(amid) {
		let dat = {stat: 0, msg: "", data: undefined}
		let moduleApplicat = await this.ModuleApplicat.findOne({
			include: [this.Application, this.Module],
			where: {id: amid}
		})
		if (!moduleApplicat) {
			dat.msg = ",模块未曾存在过,试图创建?"
			return dat
		} else if (dat.application == undefined || dat.module == undefined) {
			dat = moduleApplicat
			dat.msg = "模块不完整"
			return dat
		} else {
			dat.stat = 1
			return dat
		}
	}

	async  getAppModuleByAidMid(aid, mid) {
		let dat = {stat: 0, msg: "", data: undefined}
		let moduleApplicat = await this.ModuleApplicat.findOrCreate({
			include: [this.Application, this.Module],
			where: {aid: aid, mid: mid},
			defaults: {
				aid: aid,
				mid: mid,
				stat: true
			}
		})

		if (!moduleApplicat) {
			dat.msg = ",发生异常?"
			return dat
		} else if (moduleApplicat[0].application == undefined || moduleApplicat[0].module == undefined) {
			dat.data = moduleApplicat[0]
			dat.msg = "模块不完整"
			dat.stat = 1
			return dat
		} else {
			dat.stat = 1
			return dat
		}
	}

	/**
	 * 通过后台 aid ,mid 获取到所有的用户列表;
	 * 模块用户列表
	 * 弃用
	 */
	async getAppUser(aid, mid) {
		let query = {aid, mid}
		if (aid === 0) {
			// console.log("查找所有")
			query = {mid}
		}
		if (mid == 1) {
			let gameUserRes = await this.getEmpireUser({...query, nickname: this.ctx.query.nickname})
			return {users: gameUserRes.rows, count: gameUserRes.count}
		}
		let allRes = await this.AmoPartci.findAndCountAll({
			where: query,
			include: [{
				model: this.ApplicationUser,
				order: [["create_at", "desc"]]
			}],
			limit: this.ctx.pageListNum,
			offset: this.ctx.startPage,
		})
		let users = allRes.rows.map((params) => {
			return params.applicationUser
		})
		let obj = {users, count: allRes.count}
		return obj
	}

	async getEmpireUser({aid, oids, nickname}) {
		let query = {}
		if (aid) {
			query.aid = aid
		}
		if (Array.isArray(oids)) {
			query.oid = {
				$in: oids
			}
		}
		if (nickname) {
			query.nickname = {
				$like: `%${nickname}%`
			}
		}

		return this.EmpireUserView.findAndCountAll({
			limit: this.ctx.pageListNum,
			offset: this.ctx.startPage,
			where: query
		})
	}

	async	getModuleAppById(mid) {
		return this.Module.findOne({
			where: {
				id: mid
			},
			include: [{
				model: this.ModuleApplicat,
				include: [
					{
						model: this.Application,
						attributes: ["applicat_name", "id"]
					},
				]
			}]
		})
	}
	/*   async getUnionUser( mid) {
			return await  this.UmPartci.find({
				where: {
					mid
				},
				include: [this.ApplicationUser]
			});
		} */

	// 创建一个唯一的id
	async createUserProm({aid, openid, unionid}) {
		let uObj
		if (unionid) {
			uObj = await this.UnionUser.findOrCreate({
				defaults: {
					unionid
				},
				where: {
					unionid
				}
			})
		}

		let ipNum = this.ctx.service.server.getCurrentIpInt()

		let create = {
			aid: aid, openid, unionid: !unionid ? "" : unionid, stat: 2, subscribe_time: new Date(), ip: ipNum
		}

		this.ctx.logger.info(create)
		let appUser = await this.ApplicationUser.findOrCreate({
			where: unionid ? {openid, unionid} : {openid},
			defaults: create
		})

		return {uid: uObj !== undefined ? uObj[0].id : null, aid: aid, oid: appUser[0].id}
	}
	/**
	 * 小程序接口
	 * @param  obj 
	 */
	async updateUserInfoProm(obj) {
		if (!this.ctx.userInfo) {
			throw new Error("不合法操作")
		} else {
			let updateStat = await this.ApplicationUser.update(obj, {
				where: {
					id: this.ctx.userInfo.oid
				}
			})
			return updateStat
		}
	}

	/**
	 * 有必要做优化
	 * 小程序接口
	 * @param  obj 
	 */
	async getUserInfo() {
		if (!this.ctx.userInfo) {
			throw new Error("不合法操作")
		}
		return this.ApplicationUser.findOne({
			where: {
				id: this.ctx.userInfo.oid
			},
		})
	}
	async saveIp() {

	}
}
module.exports = AppService